#include <string.h>
#include <stdlib.h>
#include "stack.h"

int stack_init(stack_t **s, int size, int capacity)
{
	stack_t *my_s;
	// 栈结构
	my_s = malloc(sizeof(stack_t));
	if (NULL == my_s)
		return -1;
	my_s->size = size;
	my_s->top = 0;
	my_s->capacity = capacity;

	// 存储数据空间
	my_s->base = calloc(capacity, size);
	// malloc(capacity * size); + memset();
	if (NULL == my_s->base) {
		free(my_s);
		my_s = NULL;
		return -1;
	}

	*s = my_s;

	return 0;
}

int stack_empty(const stack_t *s)
{
	return 0 == s->top;
}

int stack_full(const stack_t *s)
{
	return s->top == s->capacity;
}

void stack_destroy(stack_t **s)
{
	free((*s)->base);
	(*s)->base = NULL;
	free(*s);
	*s = NULL;
}

int stack_push(stack_t *s, const void *data)
{
	if (stack_full(s))
		return -1;
	memcpy((char *)s->base + s->top * s->size, data, s->size);
	s->top ++;

	return 0;
}

int stack_pop(stack_t *s, void *data)
{
	if (stack_empty(s))
		return -1;
	s->top--;
	memcpy(data, (char *)s->base + s->top * s->size, s->size);
	memset((char *)s->base + s->top * s->size, '\0', s->size);

	return 0;
}

int stack_peek(stack_t *s, void *data)
{
	if (stack_empty(s))
		return -1;
	
	memcpy(data, (char *)s->base + s->top * s->size - 1, s->size);
}
